﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using Peak.Core.DataInterfaces;
using System.Security.Principal;
using Peak.Core;

namespace Peak.ApplicationServices.Services
{
  public class ProjectService : IProjectService
  {
    readonly IProjectRepository _projectRepository;
    private readonly IPrincipal _principal;

    public ProjectService(IProjectRepository projectRepository, IPrincipal principal)
    {
      _projectRepository = projectRepository;
      _principal = principal;
    }

    public Project Get(int id)
    {
      Project project = _projectRepository.Get(id);
      if(project == null || project.Users.FirstOrDefault(f=>f.UserName.ToLower()== _principal.Identity.Name.ToLower()) == null)
      {
        throw new EntityNotFoundException();
      }
      return project;
    }

    public Project Update(Project project)
    {
      if(project == null)
      {
        throw new ArgumentNullException("project");
      }
      if (project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      return _projectRepository.SaveOrUpdate(project);
    }   

    public void Delete(Project project)
    {
      if (project == null)
      {
        throw new ArgumentNullException("project");
      }
      if (project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      _projectRepository.Delete(project);
    }

    public IList<Project> GetAllByAssignedTo(string userName)
    {
      return _projectRepository.GetAllByAssignedTo(userName);
    }
  }
}
